package com.campus.counseling.service;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.internal.util.AlipaySignature;
import com.campus.counseling.config.AlipayConfig;
import com.campus.counseling.model.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Map;
import com.alipay.api.AlipayApiException;
import com.alibaba.fastjson.JSONObject;

@Slf4j
@Component
public class AlipayHelper {

    private final AlipayConfig alipayConfig;
    private AlipayClient alipayClient;

    public AlipayHelper(AlipayConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    @PostConstruct
    public void init() {
        try {
            alipayClient = new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),
                alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getPublicKey(),
                alipayConfig.getSignType()
            );
        } catch (Exception e) {
            log.error("初始化支付宝客户端失败", e);
            throw new RuntimeException("初始化支付宝客户端失败", e);
        }
    }

    public String createOrder(String orderNo, BigDecimal amount, String subject) throws AlipayApiException {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        request.setReturnUrl(alipayConfig.getReturnUrl());
        
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        bizContent.put("total_amount", amount.toString());
        bizContent.put("subject", subject);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        
        request.setBizContent(bizContent.toString());
        return alipayClient.pageExecute(request, "GET").getBody();
    }

    public void refund(String orderNo, BigDecimal amount, String reason) throws AlipayApiException {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        bizContent.put("refund_amount", amount.toString());
        bizContent.put("refund_reason", reason);
        
        request.setBizContent(bizContent.toString());
        
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (!response.isSuccess()) {
            throw new AlipayApiException("退款失败：" + response.getSubMsg());
        }
    }

    public boolean verifyNotify(Map<String, String> params) {
        try {
            return AlipaySignature.rsaCheckV1(params, alipayConfig.getPublicKey(), "UTF-8", "RSA2");
        } catch (Exception e) {
            log.error("验证支付宝通知失败", e);
            return false;
        }
    }
} 